<template>
  <div class="detailWrapBoxCe">
    <div @click="clearDetailIndex" class="topBack"><i></i></div>
    <div class="detailBody">
      <div class="leftBox">
        <div class="chart-container" ref="chartRef"></div>
      </div>
      <div class="rightBox">
        <div class="airport-container">
          <div class="tableTH">
            <div class="box1">起始时间（UTC）</div>
            <div class="box1">结束时间（UTC）</div>
            <div class="box2">可用性</div>
            <div class="box2">方向</div>
          </div>
          <div
            class="tableTR"
            v-for="(item, index) in currentRoute"
            :key="`route-${index}`"
          >
            <div class="box1" :style="!item.available ? 'color: #ff0004' : ''">
              {{ item.startTime }}
            </div>
            <div class="box1" :style="!item.available ? 'color: #ff0004' : ''">
              {{ item.endTime }}
            </div>
            <div
              class="box2"
              :style="item.available ? 'color: #3aff7f' : 'color: #ff0004'"
            >
              {{ item.available ? "可用" : "不可用" }}
            </div>
            <div class="box2" :style="!item.available ? 'color: #ff0004' : ''">
              {{ item.direction }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  watchEffect,
  defineProps,
  defineEmits,
  computed,
} from "vue";
import * as echarts from "echarts";

const props = defineProps({
  airTestsRouteObj: {
    type: Object,
    default: () => ({
      forwardSituations: [],
      reverseSituations: [],
      startTime: "",
      endTime: "",
      extra: { nanuPrns: [], almanacWeek: 0, secondsOfWeek: 0 },
    }),
  },
});

const emit = defineEmits(["update-curr-detail-index"]);

const currentRoute = computed(() => {
  const forwardData = (props.airTestsRouteObj.forwardSituations || []).map(
    (routeItem) => ({
      startTime: routeItem.startTime,
      endTime: routeItem.endTime,
      available: routeItem.available,
      direction: "正向",
    })
  );

  const unData = (props.airTestsRouteObj.reverseSituations || []).map(
    (routeItem) => ({
      startTime: routeItem.startTime,
      endTime: routeItem.endTime,
      available: routeItem.available,
      direction: "反向",
    })
  );

  return [...forwardData, ...unData];
});

const chartRef = ref(null);
let myChart = null;
const xAxisLabelData = ["正", "反"];
const crossDayTotalHours = 1440;

const uniqueXAxisLabelData = computed(() => {
  return xAxisLabelData;
});

const rawData = computed(() => {
  const forwardList = props.airTestsRouteObj.forwardSituations || [];
  const reverseList = props.airTestsRouteObj.reverseSituations || [];
  const maxLength = Math.max(forwardList.length, reverseList.length);
  const result = [];
  for (let i = 0; i < maxLength; i++) {
    const forwardDuration = forwardList[i]?.durationMinutes || 0;
    const reverseDuration = reverseList[i]?.durationMinutes || 0;
    result.push([forwardDuration, reverseDuration]);
  }
  console.log("航路时段时长数据（正向, 反向）:", result);
  return result;
});

const statusData = computed(() => {
  const forwardList = props.airTestsRouteObj.forwardSituations || [];
  const reverseList = props.airTestsRouteObj.reverseSituations || [];
  const maxLength = Math.max(forwardList.length, reverseList.length);
  const result = [];
  for (let i = 0; i < maxLength; i++) {
    const forwardStatus = forwardList[i]?.available ? "正向" : "反向";
    const reverseStatus = reverseList[i]?.available ? "正向" : "反向";
    result.push([forwardStatus, reverseStatus]);
  }
  console.log("航路时段状态数据（正向, 反向）:", result);
  return result;
});

const statusColors = {
  正向: "#7eed8d", // 可用-绿色
  反向: "#ed5652", // 不可用-红色
};

const balanceDailyData = () => {
  if (!rawData.value.length || !uniqueXAxisLabelData.value.length) return;

  uniqueXAxisLabelData.value.forEach((_, dayIndex) => {
    const currentSum = rawData.value.reduce(
      (sum, category) => sum + (category[dayIndex] || 0),
      0
    );
    if (Math.abs(currentSum - crossDayTotalHours) > 0.01) {
      const lastIndex = rawData.value.length - 1;
      if (lastIndex >= 0 && rawData.value[lastIndex]) {
        rawData.value[lastIndex][dayIndex] =
          (rawData.value[lastIndex][dayIndex] || 0) +
          (crossDayTotalHours - currentSum);
      } else {
        rawData.value.push([crossDayTotalHours - currentSum]);
      }
    }
  });
};

const buildSeries = () => {
  return rawData.value.map((data, seriesIndex) => ({
    name: `时段${seriesIndex + 1}`,
    type: "bar",
    stack: "total",
    barWidth: "5%", // 调宽柱子，避免过窄
    label: { show: false },
    data: data.map((value, dataIndex) => ({
      value: value || 0,
      itemStyle: {
        color: statusColors[statusData.value[seriesIndex][dataIndex] || "正向"],
      },
    })),
  }));
};

const buildChartOption = () => {
  const TEXT_SIZE = 12;
  const LABEL_OFFSET_Y = 420;

  const startDateStr = props.airTestsRouteObj.startTime || "";
  const startDate = new Date(startDateStr.replace(/-/g, "/"));

  return {
    grid: {
      left: "5%",
      right: "5%",
      top: "2%",
      bottom: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: uniqueXAxisLabelData.value.map((_, i) => i),
      axisLabel: { show: false },
      axisTick: { show: false },
      axisLine: { show: false },
      splitLine: { show: false },
    },
    yAxis: {
      type: "value",
      min: 0,
      max: crossDayTotalHours,
      interval: 360,
      axisLabel: {
        formatter: (value) => {
          const currentDate = new Date(startDate.getTime() + value * 60 * 1000);
          const month = String(currentDate.getMonth() + 1).padStart(2, "0");
          const day = String(currentDate.getDate()).padStart(2, "0");
          const hours = String(currentDate.getHours()).padStart(2, "0");
          const minutes = String(currentDate.getMinutes()).padStart(2, "0");
          return `${month}-${day}\n${hours}:${minutes}`;
        },
        fontSize: 12,
        color: "#fff",
        align: "right",
        padding: [0, 10, 0, 0],
      },
      axisLine: {
        show: true,
        lineStyle: { color: "#545f72", width: 1 },
      },
      splitLine: {
        show: true,
        lineStyle: { color: "rgba(84, 95, 114, 0.2)" },
      },
    },
    series: [
      // 自定义系列：显示"正"/"反"文本
      {
        type: "custom",
        coordinateSystem: "cartesian2d",
        renderItem: (params, api) => {
          const x = api.coord([params.dataIndex, 0])[0];
          const directionText = uniqueXAxisLabelData.value[params.dataIndex];
          return {
            type: "text",
            position: [x, LABEL_OFFSET_Y],
            style: {
              text: directionText,
              fontSize: TEXT_SIZE,
              fill: "#fff",
              textAlign: "center",
            },
          };
        },
        data: uniqueXAxisLabelData.value.map((_, i) => i),
      },
      ...buildSeries(),
    ],
    animation: true,
    animationDuration: 200,
    animationEasing: "cubicOut",
  };
};

const initChart = () => {
  if (!chartRef.value || myChart) return;
  myChart = echarts.init(chartRef.value);
  balanceDailyData();
  myChart.setOption(buildChartOption());
  // 监听窗口 resize
  window.addEventListener("resize", () => myChart?.resize());
};

const destroyChart = () => {
  window.removeEventListener("resize", () => myChart?.resize());
  if (myChart) {
    myChart.dispose();
    myChart = null;
  }
};

const clearDetailIndex = () => {
  emit("update-curr-detail-index", "");
};

onMounted(() => {
  initChart();
});

onUnmounted(() => {
  destroyChart();
});

watchEffect(() => {
  if (myChart && (rawData.value.length || statusData.value.length)) {
    balanceDailyData();
    myChart.setOption(buildChartOption());
  }
});
</script>

<style scoped lang="scss">
.detailWrapBoxCe {
  width: 100%;
  height: calc(100% - 0px);
  position: absolute;
  top: 0;
  left: 0;
  background: #070f24;
  z-index: 1;
  .topBack {
    cursor: pointer;
    width: 100%;
    height: 24px;
    margin: 16px 0;
    i {
      float: left;
      width: 24px;
      height: 24px;
      margin-left: 24px;
      background-image: url("../../../assets/images/raim/back.png");
      background-repeat: no-repeat;
      background-size: contain;
      background-position: center;
    }
  }
  .detailBody {
    width: 100%;
    height: 100%;
    overflow: hidden;
    .leftBox {
      float: left;
      width: 300px;
      padding: 20px 0;
      padding-top: 7px;
      height: 480px;
      .chart-container {
        width: 100%;
        height: 480px;
        margin: 0 auto;
      }
    }
    .rightBox {
      padding-top: 20px;
      float: right;
      width: 580px;
      height: 630px;
      .airport-container {
        height: calc(100% - 60px);
        overflow-y: auto;
        // height: 100%;
        // overflow-y: auto;
      }
      .tableTH {
        overflow: hidden;
        height: 40px;
        line-height: 40px;
        font-size: 14px;
        font-weight: 700;
        background: rgba(0, 175, 255, 0.2);
        color: #c5d6e6;
        .box1 {
          float: left;
          width: 160px;
          text-align: left;
          text-indent: 16px;
        }
        .box2 {
          float: left;
          width: 70px;
          text-align: left;
          text-indent: 16px;
        }
      }
      .tableTR {
        overflow: hidden;
        height: 40px;
        line-height: 40px;
        font-size: 14px;
        color: #c5d6e6;
        &:nth-child(even) {
          background: rgba(0, 59, 122, 0.2);
        }
        .box1 {
          float: left;
          width: 160px;
          text-align: left;
          text-indent: 16px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis; // 处理时间文本过长
        }
        .box2 {
          float: left;
          width: 70px;
          text-align: left;
          text-indent: 16px;
        }
      }
    }
  }
}
.airport-container::-webkit-scrollbar {
  width: 2px;
}
.airport-container::-webkit-scrollbar-track {
  background: rgba(6, 15, 37, 0.5);
  border-radius: 2px;
}
.airport-container::-webkit-scrollbar-thumb {
  background: rgba(0, 175, 255, 0.4);
  border-radius: 2px;
}
.airport-container::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 175, 255, 0.6);
}
.airport-container {
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 175, 255, 0.4) rgba(6, 15, 37, 0.5);
}
</style>
